import tkinter as tk
from tkinter import messagebox, simpledialog
import sqlite3
from datetime import datetime

DB_FILE = 'vip_db.sqlite'

def init_db():
    conn = sqlite3.connect(DB_FILE)
    cursor = conn.cursor()
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS members (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        phone TEXT UNIQUE NOT NULL,
        balance REAL DEFAULT 0,
        points INTEGER DEFAULT 0
    )
    ''')
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS transactions (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        phone TEXT NOT NULL,
        amount REAL,
        points INTEGER,
        timestamp TEXT,
        type TEXT
    )
    ''')
    conn.commit()
    conn.close()

def center_window(win, width, height):
    screen_w = win.winfo_screenwidth()
    screen_h = win.winfo_screenheight()
    x = (screen_w - width) // 2
    y = (screen_h - height) // 2
    win.geometry(f'{width}x{height}+{x}+{y}')

def add_member(name, phone):
    conn = sqlite3.connect(DB_FILE)
    cursor = conn.cursor()
    try:
        cursor.execute('INSERT INTO members (name, phone) VALUES (?, ?)', (name, phone))
        conn.commit()
        messagebox.showinfo("成功", f"会员 {name} 添加成功")
    except sqlite3.IntegrityError:
        messagebox.showerror("错误", "手机号已存在")
    conn.close()

def get_member_by_phone_tail(tail):
    conn = sqlite3.connect(DB_FILE)
    cursor = conn.cursor()
    cursor.execute('SELECT name, phone, balance, points FROM members WHERE phone LIKE ?', (f'%{tail}',))
    member = cursor.fetchone()
    conn.close()
    return member

def update_member_balance_points(phone, new_balance, new_points):
    conn = sqlite3.connect(DB_FILE)
    cursor = conn.cursor()
    cursor.execute('UPDATE members SET balance = ?, points = ? WHERE phone = ?', (new_balance, new_points, phone))
    conn.commit()
    conn.close()

def add_transaction(phone, amount, points, trans_type):
    conn = sqlite3.connect(DB_FILE)
    cursor = conn.cursor()
    timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    cursor.execute('INSERT INTO transactions (phone, amount, points, timestamp, type) VALUES (?, ?, ?, ?, ?)',
                   (phone, amount, points, timestamp, trans_type))
    conn.commit()
    conn.close()

def get_transactions(phone):
    conn = sqlite3.connect(DB_FILE)
    cursor = conn.cursor()
    cursor.execute('SELECT amount, points, timestamp, type FROM transactions WHERE phone = ? ORDER BY id DESC', (phone,))
    records = cursor.fetchall()
    conn.close()
    return records

def main_app(root):
    root.title("理发店VIP系统")
    root.attributes('-fullscreen', True)

    # 查询会员信息
    def load_member_info():
        tail = entry_search.get().strip()
        if not tail:
            messagebox.showwarning("提示", "请输入手机号尾号进行查询")
            return
        member = get_member_by_phone_tail(tail)
        if member:
            val_name.config(text=member[0])
            val_phone.config(text=member[1])
            val_balance.config(text=f"￥{member[2]:.1f}")
            val_points.config(text=str(member[3]))
            load_history(member[1])
            btn_recharge.config(state=tk.NORMAL)
            btn_consume.config(state=tk.NORMAL)
        else:
            messagebox.showinfo("提示", "未找到会员")
            clear_member_info()

    def clear_member_info():
        val_name.config(text="")
        val_phone.config(text="")
        val_balance.config(text="")
        val_points.config(text="")
        history_text.delete(1.0, tk.END)
        btn_recharge.config(state=tk.DISABLED)
        btn_consume.config(state=tk.DISABLED)

    # 添加会员窗口
    def add_member_window():
        win = tk.Toplevel(root)
        win.title("添加会员")
        win.resizable(False, False)
        center_window(win, 400, 220)

        tk.Label(win, text="姓名:").grid(row=0, column=0, padx=10, pady=15)
        name_e = tk.Entry(win, width=30)
        name_e.grid(row=0, column=1, padx=10, pady=15)
        tk.Label(win, text="手机号:").grid(row=1, column=0, padx=10, pady=15)
        phone_e = tk.Entry(win, width=30)
        phone_e.grid(row=1, column=1, padx=10, pady=15)

        def on_add():
            name = name_e.get().strip()
            phone = phone_e.get().strip()
            if not name or not phone:
                messagebox.showwarning("提示", "姓名和手机号不能为空")
                return
            add_member(name, phone)
            win.destroy()

        tk.Button(win, text="确认添加", width=20, command=on_add).grid(row=2, column=0, columnspan=2, pady=20)

    def recharge():
        phone = val_phone.cget("text")
        if not phone:
            messagebox.showwarning("提示", "请先查询并选中会员")
            return
        try:
            amount = float(simpledialog.askstring("充值金额", "请输入充值金额（最多1位小数）:", parent=root))
            amount = round(amount, 1)
            if amount <= 0:
                messagebox.showwarning("提示", "充值金额必须大于0")
                return
        except (TypeError, ValueError):
            messagebox.showwarning("提示", "请输入正确的数字")
            return
        # 获取当前余额和积分
        member = get_member_by_phone_tail(phone[-4:])
        if not member:
            messagebox.showerror("错误", "会员信息异常")
            return
        new_balance = member[2] + amount
        new_points = member[3] + int(amount)  # 积分为充值金额整数部分累加
        update_member_balance_points(phone, new_balance, new_points)
        add_transaction(phone, amount, int(amount), '充值')
        load_member_info()  # 刷新显示
        messagebox.showinfo("成功", f"充值成功，金额增加￥{amount:.1f}，积分增加{int(amount)}")

    def consume():
        phone = val_phone.cget("text")
        if not phone:
            messagebox.showwarning("提示", "请先查询并选中会员")
            return
        try:
            points = int(simpledialog.askstring("消费积分", "请输入消费积分:", parent=root))
            if points <= 0:
                messagebox.showwarning("提示", "消费积分必须大于0")
                return
        except (TypeError, ValueError):
            messagebox.showwarning("提示", "请输入正确的整数积分")
            return
        member = get_member_by_phone_tail(phone[-4:])
        if not member:
            messagebox.showerror("错误", "会员信息异常")
            return
        if member[3] < points:
            messagebox.showerror("错误", "积分不足")
            return
        new_points = member[3] - points
        update_member_balance_points(phone, member[2], new_points)
        add_transaction(phone, 0, -points, '消费')
        load_member_info()
        messagebox.showinfo("成功", f"消费成功，积分减少{points}")

    def load_history(phone):
        records = get_transactions(phone)
        history_text.delete(1.0, tk.END)
        if records:
            for r in records:
                history_text.insert(tk.END, f"{r[3]} - 金额: ￥{r[0]:.1f}, 积分: {r[1]}, 时间: {r[2]}\n")
        else:
            history_text.insert(tk.END, "无交易记录\n")

    # 顶部菜单区
    menu_frame = tk.Frame(root)
    menu_frame.pack(pady=10)
    tk.Button(menu_frame, text="添加会员", width=15, command=add_member_window).pack(side=tk.LEFT, padx=15)
    tk.Button(menu_frame, text="退出", width=15, command=root.destroy).pack(side=tk.LEFT, padx=15)

    # 查询区
    search_frame = tk.Frame(root)
    search_frame.pack(pady=10)
    tk.Label(search_frame, text="手机号尾号查询:").pack(side=tk.LEFT, padx=5)
    entry_search = tk.Entry(search_frame, width=20)
    entry_search.pack(side=tk.LEFT, padx=5)
    tk.Button(search_frame, text="查询", width=10, command=load_member_info).pack(side=tk.LEFT, padx=5)

    # 会员信息显示
    info_frame = tk.Frame(root)
    info_frame.pack(pady=15)

    tk.Label(info_frame, text="姓名:").grid(row=0, column=0, sticky='w', padx=10, pady=5)
    val_name = tk.Label(info_frame, text="", width=20, anchor='w')
    val_name.grid(row=0, column=1, sticky='w', padx=10, pady=5)

    tk.Label(info_frame, text="手机号:").grid(row=1, column=0, sticky='w', padx=10, pady=5)
    val_phone = tk.Label(info_frame, text="", width=20, anchor='w')
    val_phone.grid(row=1, column=1, sticky='w', padx=10, pady=5)

    tk.Label(info_frame, text="金额:").grid(row=2, column=0, sticky='w', padx=10, pady=5)
    val_balance = tk.Label(info_frame, text="", width=20, anchor='w')
    val_balance.grid(row=2, column=1, sticky='w', padx=10, pady=5)

    tk.Label(info_frame, text="积分:").grid(row=3, column=0, sticky='w', padx=10, pady=5)
    val_points = tk.Label(info_frame, text="", width=20, anchor='w')
    val_points.grid(row=3, column=1, sticky='w', padx=10, pady=5)

    # 操作按钮区
    op_frame = tk.Frame(root)
    op_frame.pack(pady=10)
    btn_recharge = tk.Button(op_frame, text="充值", width=15, command=recharge, state=tk.DISABLED)
    btn_recharge.pack(side=tk.LEFT, padx=10)
    btn_consume = tk.Button(op_frame, text="消费积分", width=15, command=consume, state=tk.DISABLED)
    btn_consume.pack(side=tk.LEFT, padx=10)

    # 交易记录显示
    history_frame = tk.Frame(root)
    history_frame.pack(pady=10, fill=tk.BOTH, expand=True)
    tk.Label(history_frame, text="交易记录:").pack(anchor='w', padx=10)
    history_text = tk.Text(history_frame, height=12, width=80)
    history_text.pack(padx=10, pady=5, fill=tk.BOTH, expand=True)

    # 初始化清空界面
    clear_member_info()

def login_window():
    login_root = tk.Tk()
    login_root.title("管理员登录")
    login_root.resizable(False, False)
    center_window(login_root, 300, 180)

    tk.Label(login_root, text="用户名:").pack(pady=10)
    user_entry = tk.Entry(login_root)
    user_entry.pack()

    tk.Label(login_root, text="密码:").pack(pady=10)
    pwd_entry = tk.Entry(login_root, show='*')
    pwd_entry.pack()

    def try_login():
        user = user_entry.get()
        pwd = pwd_entry.get()
        if user == 'admin' and pwd == 'zyp123':
            login_root.destroy()
            root = tk.Tk()
            main_app(root)
            root.mainloop()
        else:
            messagebox.showerror("错误", "用户名或密码错误")

    tk.Button(login_root, text="登录", width=10, command=try_login).pack(pady=15)

    login_root.mainloop()

def main():
    init_db()
    login_window()

if __name__ == '__main__':
    main()
